import React, { useState, useEffect } from 'react';
import { Card, Form, Input, Button, Select, DatePicker, InputNumber, message, Spin, Row, Col, Divider } from 'antd';
import { ArrowLeftOutlined, SaveOutlined } from '@ant-design/icons';
import { useParams, useNavigate } from 'react-router-dom';
import dayjs from 'dayjs';

// 引入API
import { getSalary, createSalary, updateSalary } from '../../../api/salary';
import { listEmployees } from '../../../api/employee';

const { Option } = Select;

const SalaryForm = () => {
    const { id } = useParams();
    const navigate = useNavigate();
    const [form] = Form.useForm();
    const [loading, setLoading] = useState(false);
    const [initialLoading, setInitialLoading] = useState(false);
    const [employees, setEmployees] = useState([]);
    const [totalIncome, setTotalIncome] = useState(0);
    const [totalDeduction, setTotalDeduction] = useState(0);
    const [netSalary, setNetSalary] = useState(0);

    // 判断是否为编辑模式
    const isEditMode = !!id;

    useEffect(() => {
        fetchEmployees();
        if (isEditMode) {
            fetchSalaryDetail();
        }
    }, [id]);

    // 监听表单值变化，计算实发工资
    useEffect(() => {
        const formValues = form.getFieldsValue();
        calculateSalary(formValues);
    }, [form.getFieldsValue()]);

    // 获取员工列表
    const fetchEmployees = async () => {
        try {
            setLoading(true);
            const response = await listEmployees({ pageSize: 1000 }); // 获取所有员工
            setEmployees(response.data || []);
        } catch (error) {
            console.error('获取员工列表失败:', error);
            message.error('获取员工列表失败');
        } finally {
            setLoading(false);
        }
    };

    // 获取薪资详情（编辑模式）
    const fetchSalaryDetail = async () => {
        try {
            setInitialLoading(true);
            const response = await getSalary(id);
            const salaryData = response.data;
            
            // 格式化日期字段
            if (salaryData.paymentDate) {
                salaryData.paymentDate = dayjs(salaryData.paymentDate);
            }
            
            form.setFieldsValue(salaryData);
            calculateSalary(salaryData);
        } catch (error) {
            console.error('获取薪资详情失败:', error);
            message.error('获取薪资详情失败');
        } finally {
            setInitialLoading(false);
        }
    };

    // 计算薪资
    const calculateSalary = (values) => {
        const baseSalary = Number(values.baseSalary) || 0;
        const bonus = Number(values.bonus) || 0;
        const overtime = Number(values.overtime) || 0;
        const subsidy = Number(values.subsidy) || 0;
        const otherIncome = Number(values.otherIncome) || 0;
        
        const insurance = Number(values.insurance) || 0;
        const tax = Number(values.tax) || 0;
        const housingFund = Number(values.housingFund) || 0;
        const leaveDeduction = Number(values.leaveDeduction) || 0;
        const otherDeduction = Number(values.otherDeduction) || 0;
        
        const income = baseSalary + bonus + overtime + subsidy + otherIncome;
        const deduction = insurance + tax + housingFund + leaveDeduction + otherDeduction;
        const net = income - deduction;
        
        setTotalIncome(income);
        setTotalDeduction(deduction);
        setNetSalary(net);
    };

    // 表单值变化时重新计算
    const handleValuesChange = (changedValues, allValues) => {
        calculateSalary(allValues);
    };

    // 提交表单
    const handleSubmit = async (values) => {
        try {
            setLoading(true);
            
            // 准备提交的数据
            const salaryData = {
                ...values,
                netSalary: netSalary // 添加计算得到的实发工资
            };
            
            // 格式化日期
            if (salaryData.paymentDate) {
                salaryData.paymentDate = salaryData.paymentDate.format('YYYY-MM-DD');
            }
            
            if (isEditMode) {
                // 编辑薪资记录
                await updateSalary(id, salaryData);
                message.success('薪资记录更新成功');
            } else {
                // 添加薪资记录
                await createSalary(salaryData);
                message.success('薪资记录添加成功');
            }
            
            // 返回列表页
            navigate('/salary');
        } catch (error) {
            console.error('保存薪资记录失败:', error);
            message.error('保存薪资记录失败');
        } finally {
            setLoading(false);
        }
    };

    // 返回列表
    const handleBack = () => {
        navigate('/salary');
    };

    if (initialLoading) {
        return <Spin size="large" className="global-spin" />;
    }

    return (
        <div className="salary-form-container">
            <Card
                title={isEditMode ? '编辑薪资记录' : '添加薪资记录'}
                extra={
                    <Button icon={<ArrowLeftOutlined />} onClick={handleBack}>
                        返回
                    </Button>
                }
            >
                <Form
                    form={form}
                    layout="vertical"
                    onFinish={handleSubmit}
                    onValuesChange={handleValuesChange}
                    initialValues={{
                        baseSalary: 0,
                        bonus: 0,
                        overtime: 0,
                        subsidy: 0,
                        otherIncome: 0,
                        insurance: 0,
                        tax: 0,
                        housingFund: 0,
                        leaveDeduction: 0,
                        otherDeduction: 0,
                        status: 0,
                        year: dayjs().format('YYYY'),
                        month: dayjs().format('M')
                    }}
                >
                    <Divider orientation="left">基本信息</Divider>
                    <Row gutter={24}>
                        <Col span={8}>
                            <Form.Item
                                name="userId"
                                label="员工"
                                rules={[{ required: true, message: '请选择员工' }]}
                            >
                                <Select
                                    placeholder="请选择员工"
                                    loading={loading}
                                    showSearch
                                    optionFilterProp="children"
                                >
                                    {employees.map(emp => (
                                        <Option key={emp.id} value={emp.id}>
                                            {emp.name} ({emp.employeeId || emp.id})
                                        </Option>
                                    ))}
                                </Select>
                            </Form.Item>
                        </Col>
                        <Col span={8}>
                            <Form.Item
                                name="year"
                                label="年份"
                                rules={[{ required: true, message: '请输入年份' }]}
                            >
                                <Input placeholder="请输入年份，如：2023" />
                            </Form.Item>
                        </Col>
                        <Col span={8}>
                            <Form.Item
                                name="month"
                                label="月份"
                                rules={[{ required: true, message: '请输入月份' }]}
                            >
                                <Select placeholder="请选择月份">
                                    {Array.from({ length: 12 }, (_, i) => i + 1).map(month => (
                                        <Option key={month} value={month.toString()}>{month}月</Option>
                                    ))}
                                </Select>
                            </Form.Item>
                        </Col>
                    </Row>

                    <Row gutter={24}>
                        <Col span={8}>
                            <Form.Item
                                name="status"
                                label="状态"
                                rules={[{ required: true, message: '请选择状态' }]}
                            >
                                <Select placeholder="请选择状态">
                                    <Option value={0}>未发放</Option>
                                    <Option value={1}>已发放</Option>
                                </Select>
                            </Form.Item>
                        </Col>
                        <Col span={8}>
                            <Form.Item
                                name="paymentDate"
                                label="发放日期"
                            >
                                <DatePicker style={{ width: '100%' }} placeholder="请选择发放日期" />
                            </Form.Item>
                        </Col>
                    </Row>

                    <Divider orientation="left">收入项</Divider>
                    <Row gutter={24}>
                        <Col span={8}>
                            <Form.Item
                                name="baseSalary"
                                label="基本工资"
                                rules={[{ required: true, message: '请输入基本工资' }]}
                            >
                                <InputNumber
                                    style={{ width: '100%' }}
                                    min={0}
                                    precision={2}
                                    placeholder="请输入基本工资"
                                    formatter={value => `¥ ${value}`.replace(/\B(?=(\d{3})+(?!\d))/g, ',')}
                                    parser={value => value.replace(/¥\s?|(,*)/g, '')}
                                />
                            </Form.Item>
                        </Col>
                        <Col span={8}>
                            <Form.Item
                                name="bonus"
                                label="绩效奖金"
                            >
                                <InputNumber
                                    style={{ width: '100%' }}
                                    min={0}
                                    precision={2}
                                    placeholder="请输入绩效奖金"
                                    formatter={value => `¥ ${value}`.replace(/\B(?=(\d{3})+(?!\d))/g, ',')}
                                    parser={value => value.replace(/¥\s?|(,*)/g, '')}
                                />
                            </Form.Item>
                        </Col>
                        <Col span={8}>
                            <Form.Item
                                name="overtime"
                                label="加班费"
                            >
                                <InputNumber
                                    style={{ width: '100%' }}
                                    min={0}
                                    precision={2}
                                    placeholder="请输入加班费"
                                    formatter={value => `¥ ${value}`.replace(/\B(?=(\d{3})+(?!\d))/g, ',')}
                                    parser={value => value.replace(/¥\s?|(,*)/g, '')}
                                />
                            </Form.Item>
                        </Col>
                    </Row>

                    <Row gutter={24}>
                        <Col span={8}>
                            <Form.Item
                                name="subsidy"
                                label="补贴"
                            >
                                <InputNumber
                                    style={{ width: '100%' }}
                                    min={0}
                                    precision={2}
                                    placeholder="请输入补贴"
                                    formatter={value => `¥ ${value}`.replace(/\B(?=(\d{3})+(?!\d))/g, ',')}
                                    parser={value => value.replace(/¥\s?|(,*)/g, '')}
                                />
                            </Form.Item>
                        </Col>
                        <Col span={8}>
                            <Form.Item
                                name="otherIncome"
                                label="其他收入"
                            >
                                <InputNumber
                                    style={{ width: '100%' }}
                                    min={0}
                                    precision={2}
                                    placeholder="请输入其他收入"
                                    formatter={value => `¥ ${value}`.replace(/\B(?=(\d{3})+(?!\d))/g, ',')}
                                    parser={value => value.replace(/¥\s?|(,*)/g, '')}
                                />
                            </Form.Item>
                        </Col>
                        <Col span={8}>
                            <div className="salary-summary-item">
                                <span className="label">收入合计：</span>
                                <span className="value">¥ {totalIncome.toLocaleString('zh-CN', { minimumFractionDigits: 2, maximumFractionDigits: 2 })}</span>
                            </div>
                        </Col>
                    </Row>

                    <Divider orientation="left">扣除项</Divider>
                    <Row gutter={24}>
                        <Col span={8}>
                            <Form.Item
                                name="insurance"
                                label="社保"
                            >
                                <InputNumber
                                    style={{ width: '100%' }}
                                    min={0}
                                    precision={2}
                                    placeholder="请输入社保金额"
                                    formatter={value => `¥ ${value}`.replace(/\B(?=(\d{3})+(?!\d))/g, ',')}
                                    parser={value => value.replace(/¥\s?|(,*)/g, '')}
                                />
                            </Form.Item>
                        </Col>
                        <Col span={8}>
                            <Form.Item
                                name="tax"
                                label="个人所得税"
                            >
                                <InputNumber
                                    style={{ width: '100%' }}
                                    min={0}
                                    precision={2}
                                    placeholder="请输入个人所得税"
                                    formatter={value => `¥ ${value}`.replace(/\B(?=(\d{3})+(?!\d))/g, ',')}
                                    parser={value => value.replace(/¥\s?|(,*)/g, '')}
                                />
                            </Form.Item>
                        </Col>
                        <Col span={8}>
                            <Form.Item
                                name="housingFund"
                                label="公积金"
                            >
                                <InputNumber
                                    style={{ width: '100%' }}
                                    min={0}
                                    precision={2}
                                    placeholder="请输入公积金"
                                    formatter={value => `¥ ${value}`.replace(/\B(?=(\d{3})+(?!\d))/g, ',')}
                                    parser={value => value.replace(/¥\s?|(,*)/g, '')}
                                />
                            </Form.Item>
                        </Col>
                    </Row>

                    <Row gutter={24}>
                        <Col span={8}>
                            <Form.Item
                                name="leaveDeduction"
                                label="请假扣款"
                            >
                                <InputNumber
                                    style={{ width: '100%' }}
                                    min={0}
                                    precision={2}
                                    placeholder="请输入请假扣款"
                                    formatter={value => `¥ ${value}`.replace(/\B(?=(\d{3})+(?!\d))/g, ',')}
                                    parser={value => value.replace(/¥\s?|(,*)/g, '')}
                                />
                            </Form.Item>
                        </Col>
                        <Col span={8}>
                            <Form.Item
                                name="otherDeduction"
                                label="其他扣除"
                            >
                                <InputNumber
                                    style={{ width: '100%' }}
                                    min={0}
                                    precision={2}
                                    placeholder="请输入其他扣除"
                                    formatter={value => `¥ ${value}`.replace(/\B(?=(\d{3})+(?!\d))/g, ',')}
                                    parser={value => value.replace(/¥\s?|(,*)/g, '')}
                                />
                            </Form.Item>
                        </Col>
                        <Col span={8}>
                            <div className="salary-summary-item">
                                <span className="label">扣除合计：</span>
                                <span className="value">¥ {totalDeduction.toLocaleString('zh-CN', { minimumFractionDigits: 2, maximumFractionDigits: 2 })}</span>
                            </div>
                        </Col>
                    </Row>

                    <Divider orientation="left">其他信息</Divider>
                    <Row gutter={24}>
                        <Col span={24}>
                            <Form.Item
                                name="remark"
                                label="备注"
                            >
                                <Input.TextArea rows={4} placeholder="请输入备注信息" />
                            </Form.Item>
                        </Col>
                    </Row>

                    <div className="salary-total-summary">
                        <div className="net-salary">
                            <span className="label">实发工资：</span>
                            <span className="value">¥ {netSalary.toLocaleString('zh-CN', { minimumFractionDigits: 2, maximumFractionDigits: 2 })}</span>
                        </div>
                    </div>

                    <div className="form-actions">
                        <Button type="default" onClick={handleBack} style={{ marginRight: 8 }}>
                            取消
                        </Button>
                        <Button type="primary" htmlType="submit" loading={loading} icon={<SaveOutlined />}>
                            保存
                        </Button>
                    </div>
                </Form>
            </Card>
        </div>
    );
};

export default SalaryForm;